/**
 * Created by qiuyuwu on 17/6/20.
 */
(function($) {

    function calendarWidget(el, params) {

        var now   = new Date();
        var thismonth = now.getMonth();
        var thisyear  = now.getYear() + 1900;
        var thisday=now.getDate();

        //console.log(thisyear,thismonth,thisday);

        var opts = {
            month: thismonth,
            year: thisyear,
            startTime:null,
            endTime:null
        };

        //console.log(thisyear,thismonth,thisday);

        $.extend(opts, params);

        var startTime=opts.startTime;
        var endTime=opts.endTime;

        //console.log(opts);

        var monthNames = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
        var dayNames = ['日', '一', '二', '三', '四', '五', '六'];
        month = i = parseInt(opts.month);
        year = parseInt(opts.year);
        var m = 0;
        var table = '';


        table += ('<h3 class="date-title">'+year+'年'+monthNames[month]+'月</h3>');
        table += ('<table class="calender-table" ' +'id="calendar-month'+i+' " cellspacing="0" data-year="'+year+'" data-month="'+monthNames[month]+'">');
        table += '<thead>';
        table += '<tr>';

        for (d=0; d<7; d++) {
            table += '<th class="weekday">' + dayNames[d] + '</th>';
        }

        table += '</tr>';
        table += '</thead>';

        var days = getDaysInMonth(month,year);
        var firstDayDate=new Date(year,month,1);
        var firstDay=firstDayDate.getDay();

        var prev_days = getDaysInMonth(month,year);
        var firstDayDate=new Date(year,month,1);
        var firstDay=firstDayDate.getDay();

        var prev_m = month == 0 ? 11 : month-1;
        var prev_y = prev_m == 11 ? year - 1 : year;
        var prev_days = getDaysInMonth(prev_m, prev_y);
        firstDay = (firstDay == 0 && firstDayDate) ? 7 : firstDay;

        var i = 0;
        for (j=0;j<42;j++){

            if ((j<firstDay)){
                table += ('<td class="disabled"><span class="day" style="display: none">'+ (prev_days-firstDay+j+1) +'</span></td>');
            } else if ((j>=firstDay+getDaysInMonth(month,year))) {
                //i = i+1;
                //table += ('<td class="disabled"><span class="day" style="display: none">'+ i +'</span></td>');
            }else{
                if(startTime!=null&&month==startTime.month&&year==startTime.year&&(j-firstDay+1)<startTime.date){
                    table += ('<td class="disabled"><span class="day">'+(j-firstDay+1)+'</span></td>');
                }else if(month==thismonth&&year==thisyear&&(j-firstDay+1)==thisday){
                    table += ('<td data-date="'+(j-firstDay+1)+'" data-year="'+year+'" data-month="'+monthNames[month]+'" class="current-month today"><span class="day">今天</span></td>');
                }else if(endTime!=null&&month==endTime.month&&year==endTime.year&&(j-firstDay+1)>endTime.date){
                    table += ('<td class="disabled"><span class="day">'+(j-firstDay+1)+'</span></td>');
                }else{
                    table += ('<td data-date="'+(j-firstDay+1)+'" data-year="'+year+'" data-month="'+monthNames[month]+'" class="current-month"><span class="day">'+(j-firstDay+1)+'</span></td>');
                }
            }
            if (j%7==6)  table += ('</tr>');
        }

        table += ('</table>');
        return table;
        //el.html(table);
    }

    function getDaysInMonth(month,year)  {
        var daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];
        if ((month==1)&&(year%4==0)&&((year%100!=0)||(year%400==0))){
            return 29;
        }else{
            return daysInMonth[month];
        }
    }

    function   formatDate(now)   {


        var   year=now.getFullYear();
        var   month=now.getMonth();
        var   date=now.getDate();
        var   hour=now.getHours();
        var   minute=now.getMinutes();
        var   second=now.getSeconds();

        return {
            year:year,
            month:month,
            date:date,
            hour:hour,
            minute:minute,
            second:second
        };



        //return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
    }


    // jQuery plugin initialisation
    $.fn.calendarWidget = function(params) {

        var option={
            startTime:new Date(),
            dateNumber:30,
            checkFun:function(date) {

            }
        };

        $.extend(option, params);


        var startYear=option.startTime.getFullYear();
        var startMonth=option.startTime.getMonth();
        var startDay=option.startTime.getDate();


        var endDate=formatDate( new Date(option.startTime.getTime()+option.dateNumber*24*60*60*1000));

        //console.log(endDate);

        var monthNumber=endDate.year==startYear?endDate.month-startMonth:endDate.month+1+11-startMonth;

         //console.log(monthNumber);

        var html="";

        for(var i=0; i<=monthNumber;i++){
           html+=calendarWidget(this,{
                year:(startMonth+i)<=11?startYear:startYear+Math.ceil((startMonth+i)/11-1),
                month:(startMonth+i)>11?startMonth+i-12:startMonth+i,
                startTime:{
                   year:startYear,
                   month:startMonth,
                   date:startDay
                },
                endTime:endDate
           });
        }


        //calendarWidget(this, params);
        $(this).html(html);

        var that=this;

        $(this).on('click','td.current-month',function () {
            that.find('td.current-month').removeClass('active');
            $(this).addClass('active');
            //var data=$(this).attr('data-year')+'年'+$(this).attr('data-month')+'月'+$(this).attr('data-date')+'日';

            var data=new Date($(this).attr('data-year'),$(this).attr('data-month')-1,$(this).attr('data-date'));

            option.checkFun(data);

        });
        return this;

    };

})($);

function checkDate(option) {
    var defaultOpt = {
        elem: "",
        arrivalDate: new Date(),
        dayNumber: 1,
        leaveDate: new Date(),
        term: 90,
        sureCallback: function (date) {
            //console.log(date);
        }
    };
    var that = this;
    $.extend(defaultOpt, option);


    this.dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    this.dayNumber = defaultOpt.dayNumber;
    this.arrivalDate = defaultOpt.arrivalDate;
    this.leaveDate = defaultOpt.leaveDate;
    this.sureCallback = defaultOpt.sureCallback;
    this.term=defaultOpt.term;

    var formatDate=function   (now) {

        var year = now.getFullYear();
        var month = now.getMonth()+1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();

        month=month<10?'0'+month:month;

        date=date<10?'0'+date:date;

        return {
            year: year,
            month: month,
            date: date,
            hour: hour,
            minute: minute,
            second: second,
            day:['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()]
        };
    }


    this.getInfo=function () {
        return {
            arrivalDate: formatDate(this.arrivalDate),
            dayNumber:that.dayNumber,
            leaveDate: formatDate(this.leaveDate)
        }
    };



    if ($("#popLayer").length != 1) {
        this.createPopElm();
        this.upDataPop();
        this.bindPop();
    }


    // $(this.elem).on('click',function(){
    //     that.showPop();
    // });


};

checkDate.prototype = {
    createPopElm: function () {
        var html = '<aside id="popLayer" class="pop-layer"></aside>' +
            '<aside id="CheckDayPop" class="check-day-pop">' +
            '<ul class="default-list">' +
            '<li id="checkStart">' +
            '<div class="item-inner">' +
            '<div class="item-center">' +
            '<span class="time">6月21日</span>' +
            '</div>' +
            '<div class="item-right">' +
            '周三 <span>入住</span>' +
            '</div>' +
            '<div class="item-after"><i class="iconfont icon-more"></i></div>' +
            '</div>' +
            '</li>' +
            '<li>' +
            '<div class="item-inner">' +
            '<div id="dayNumber" class="item-center">住4晚</div>' +
            '<div id="dayDate" class="item-right">' +
            '06月21日周三 <span>离店</span>' +
            '</div>' +
            '<div class="item-after">' +
            '<div class="room-number">' +
            '<span class="btn-cut">-</span>' +
            '<span  class="btn-add">+</span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</li>' +
            '</ul>' +
            '<a id="sureCheckDateBtn" class="button button-primary" href="javascript:void(0);">确定</a>' +
            '</aside>';
        $('body').append(html);
        this.upDataPop();
    },
    bindPop: function () {
        var that = this;
        var cutBtn = $("#CheckDayPop").find('.btn-cut');
        var addBtn = $("#CheckDayPop").find('.btn-add');
        var checkStart = $("#checkStart");
        var sureBtn = $("#sureCheckDateBtn");


        checkStart.click(function () {
            if ($('.page-check-day').length != 1) {
                that.initfun();
            }
            that.showDate();
        });


        cutBtn.click(function () {
            that.dayNumber = that.dayNumber - 1 <= 0 ? 1 : that.dayNumber - 1;
            that.upDataPop();

        });
        addBtn.click(function () {
            that.dayNumber = that.dayNumber + 1 > 100 ? 100 : that.dayNumber + 1;
            that.upDataPop();
        });


        $('#popLayer').click(function () {
            that.hidePop();
        });

        sureBtn.click(function () {
            that.hidePop();
            that.sureCallback(that.getInfo());
        });
    },
    upDataPop: function () {
        var date = this.arrivalDate;
        var leaveDate;
        var dayNames=this.dayNames;
        var dayNumber=this.dayNumber;
        this.leaveDate = new Date(date.getTime() + dayNumber * 24 * 60 * 60 * 1000);
        leaveDate=this.leaveDate;



        $("#checkStart").html(
            '<div class="item-inner">' +
            '<div class="item-center">' +
            '<span class="time">' + (date.getMonth() + 1) + '月' + (date.getDate(0)) + '日</span>' +
            '</div>' +
            '<div class="item-right">' + dayNames[date.getDay()] + '<span>入住</span></div>' +
            '<div class="item-after"><i class="iconfont icon-more"></i></div>' +
            '</div>'
        );
        $('#dayNumber').html('住' + dayNumber + '晚');
        $('#dayDate').html(leaveDate.getMonth() + 1 + '月' + leaveDate.getDate() + '日' + dayNames[leaveDate.getDay()] + '<span>离店</span>');
    },
    showPop: function () {
        $('#popLayer').addClass('active');
        $("#CheckDayPop").addClass('active');
    },
    hidePop: function () {
        $('#popLayer').removeClass('active');
        $("#CheckDayPop").removeClass('active');
    },
    initfun: function () {
        var that = this;
        var html = '<section class="page-wrap page-check-day">' +
            '    <header class="header-box">' +
            '<aside class="header-content">' +
            '<div class="left-tool">' +
            '<a id="dateCancel" class="back" href="javascript:void(0);"><i class="iconfont icon-back"></i>取消</a>' +
            '</div>' +
            '<div class="title">旅行日期</div>' +
            '</aside>' +
            '</header>' +
            '<section>' +
            '<aside class="check-day-calender">' +
            '<aside id="calendar"></aside>' +
            '</aside>' +
            '</section>' +
            ' </section>';

        $('body').append(html);

        $("#calendar").calendarWidget({
            startTime: new Date(),
            dateNumber:that.term,
            checkFun: function (date) {  //date like Date；
               // console.log(date);
                that.hideDate();
                that.dayNumber = 1;
                that.arrivalDate = date;
                that.upDataPop();


            }
        });

        $('#dateCancel').click(function () {
            that.hideDate();
        });

    },
    showDate: function () {
        $('body').css({overflow: 'hidden'});
        $(".page-check-day").addClass('active');
    },
    hideDate: function () {
        $('body').css({overflow: ""});
        $(".page-check-day").removeClass('active');
    },
};
